import axios from 'axios'

const { key } = useGlobalState()
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 30000,
  withCredentials: false,
})

service.interceptors.request.use(
  (request) => {
    openLoading()
    request.headers['token-key'] = key.value
    return request
  },
  (err) => {
    showFailToast('无法发送请求')
    return Promise.reject(err.data)
  },
)

//拦截返回值
service.interceptors.response.use(
  async (response) => {
    const {
      data: res,
      data: { code, data, msg },
    } = response
    closeLoading()

    if (code != 200) {
      showFailToast(msg || '程序异常')
      return Promise.reject(res)
    }
    return Promise.resolve(data)
  },
  (err) => {
    closeLoading()
    if (!err.request) showFailToast('请求异常')
    else {
      const { status: code } = err.request
      if (code == 404) showFailToast('未知的请求')
      else showFailToast('请求服务器异常')
    }
    return Promise.reject(err)
  },
)
export default service
